<template>
	<view class="order-list">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<!-- 顶部栏 -->
				<view class="top-bar">
					<view class="left">
						<view class="back-btn" @tap="goBack">
							<uv-icon name="arrow-left" size="24" color="#333" bold></uv-icon>
						</view>
					</view>
					<view class="search-box">
						<uv-icon name="search" size="32" color="#999"></uv-icon>
						<input class="search-input" v-model="searchKeyword" placeholder="搜索订单商品" @confirm="handleSearch"
							confirm-type="search" />
						<view class="clear-btn" v-if="searchKeyword" @tap="clearSearch">
							<uv-icon name="close" size="24" color="#999"></uv-icon>
						</view>
					</view>
				</view>
				
				<!-- 状态标签栏 -->
				<scroll-view class="status-tabs" scroll-x>
					<view class="tab-item" v-for="(tab, index) in statusTabs" :key="index"
						:class="{ active: currentStatus === tab.value }" @tap="switchStatus(tab.value)">
						<text>{{tab.label}}</text>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-scroll" scroll-y refresher-enabled :refresher-triggered="refreshing"
			@refresherrefresh="onRefresh" @scrolltolower="loadMore">
			<view class="order-content">
				<!-- 骨架屏 -->
				<view class="skeleton-wrapper" v-if="skeletonLoading">
					<uv-skeletons :loading="skeletonLoading" :skeleton="skeleton"></uv-skeletons>
				</view>
				
				<!-- 订单列表 -->
				<template v-else>
					<view class="order-item" v-for="order in orderList" :key="order.id" @tap="goToDetail(order.id)">
						<view class="order-header">
							<text class="order-no">订单号：{{order.orderNo}}</text>
							<text class="order-status">{{getStatusText(order.status)}}</text>
						</view>

						<view class="goods-info">
							<image class="goods-image" :src="order.goods.mainImages[0].imageUrl" mode="aspectFill"></image>
							<view class="goods-detail">
								<text class="goods-name">{{order.goods.name}}</text>
								<view class="price-info">
									<template v-if="order.paymentType === 1">
										<text class="price">¥{{order.totalAmount}}</text>
									</template>
									<template v-else-if="order.paymentType === 2">
										<text class="points">{{order.pointsCount}}积分</text>
									</template>
									<template v-else-if="order.paymentType === 3">
										<text class="mixed">{{order.pointsCount}}积分 + ¥{{order.payAmount}}</text>
									</template>
									<template v-else>
										<text
											class="gift">{{order.paymentType === 4 ? order.giftCardCount + '张礼品卡' : order.voucherCount + '张礼品券'}}</text>
									</template>
									<text class="count">x{{order.goodsCount}}</text>
								</view>
							</view>
						</view>

						<view class="order-footer">
							<text class="time">{{formatDate(order.createTime, 'YYYY-MM-DD HH:mm')}}</text>
							<view class="action-btns">
								<template v-if="order.status === 0">
									<button class="btn cancel-btn" @tap.stop="cancelOrder(order.id)">取消订单</button>
									<button class="btn pay-btn" @tap.stop="payOrder(order.id)">立即支付</button>
								</template>
								<!-- <button v-else-if="order.status === 3" class="btn delete-btn"
									@tap.stop="deleteOrder(order.id)">删除订单</button> -->
							</view>
						</view>
					</view>

					<!-- 加载更多 -->
					<view class="load-more" v-if="orderList.length">
						<text v-if="loading">加载中...</text>
						<text v-else-if="finished">没有更多了</text>
					</view>

					<!-- 空状态 -->
					<view class="empty-wrapper" v-if="!loading && !orderList.length">
						<uv-empty mode="order" text="暂无相关订单" :show="true" marginTop="120">
							<template #bottom>
								<button class="go-shopping" @tap="goShopping">
									去逛逛
								</button>
							</template>
						</uv-empty>
					</view>
				</template>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		formatDate
	} from '@/utils/date.js'

	export default {
		data() {
			return {
				statusBarHeight: 0,
				searchKeyword: '',
				currentStatus: -1,
				statusTabs: [{
						label: '全部',
						value: -1
					},
					{
						label: '待支付',
						value: 0
					},
					{
						label: '待收货',
						value: 6
					},
					{
						label: '已支付',
						value: 1
					},
					{
						label: '已完成',
						value: 2
					},
					{
						label: '已取消',
						value: 3
					},
					{
						label: '已退款',
						value: 4
					},
					{
						label: '超时未支付',
						value: 5
					}
				],
				orderList: [],
				pageNum: 1,
				pageSize: 10,
				total: 0,
				loading: false,
				finished: false,
				refreshing: false,
				skeletonLoading: true,
				skeleton: [{
					type: 'flex',
					children: [{
						type: 'custom',
						style: 'width:160rpx;height:160rpx;marginRight:20rpx;borderRadius:8rpx;'
					}, {
						type: 'line',
						num: 3,
						style: [null, 'width:360rpx;', 'width:200rpx;']
					}]
				}, 20, {
					type: 'flex',
					children: [{
						type: 'custom',
						style: 'width:160rpx;height:160rpx;marginRight:20rpx;borderRadius:8rpx;'
					}, {
						type: 'line',
						num: 3,
						style: [null, 'width:360rpx;', 'width:200rpx;']
					}]
				}, 20, {
					type: 'flex',
					children: [{
						type: 'custom',
						style: 'width:160rpx;height:160rpx;marginRight:20rpx;borderRadius:8rpx;'
					}, {
						type: 'line',
						num: 3,
						style: [null, 'width:360rpx;', 'width:200rpx;']
					}]
				}]
			}
		},

		onLoad() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight
			this.loadOrders()
		},

		methods: {
			formatDate,

			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 清除搜索
			clearSearch() {
				this.searchKeyword = ''
				this.resetList()
			},

			// 处理搜索
			handleSearch() {
				uni.$uv.debounce(this.resetList(), 500)
			},

			// 切换状态
			switchStatus(status) {
				this.currentStatus = status
				this.resetList()
			},

			// 重置列表
			resetList() {
				this.pageNum = 1
				this.orderList = []
				this.finished = false
				this.skeletonLoading = true
				this.loadOrders()
			},

			// 获取订单列表
			async loadOrders() {
				if (this.loading || this.finished) return

				this.loading = true
				try {
					const params = {
						goodsName: this.searchKeyword,
						status: this.currentStatus === -1 ? undefined : this.currentStatus,
						pageNum: this.pageNum,
						pageSize: this.pageSize
					}

					const {
						items,
						count
					} = await this.$http.post('/mall/order/list', params)

					this.total = count
					this.orderList = this.pageNum === 1 ? items : [...this.orderList, ...items]
					this.finished = this.orderList.length >= count
					this.pageNum++
				} catch (e) {
					uni.showToast({
						title: '获取订单列表失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					this.refreshing = false
					this.skeletonLoading = false
				}
			},

			// 下拉刷新
			onRefresh() {
				this.refreshing = true
				this.resetList()
			},

			// 加载更多
			loadMore() {
				this.loadOrders()
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					0: '待支付',
					1: '已支付',
					2: '已完成',
					3: '已取消',
					4: '已退款',
					5: '超时未支付',
					6: '待收货'
				}
				return statusMap[status] || '未知状态'
			},

			// 跳转详情
			goToDetail(orderId) {
				uni.navigateTo({
					url: `/subpkg/order_detail/order_detail?orderId=${orderId}`
				})
			},

			// 取消订单
			cancelOrder(orderId) {
				uni.showModal({
					title: '提示',
					content: '确定要取消该订单吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$http.post(`/mall/order/cancel/${orderId}`)
								this.resetList()
							} catch (e) {
								uni.showToast({
									title: '取消订单失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			// 支付订单
			payOrder(orderId) {
				// TODO: 实现支付逻辑
			},

			// 删除订单
			deleteOrder(orderId) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该订单吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$http.delete(`/mall/order/${orderId}`)
								this.resetList()
							} catch (e) {
								uni.showToast({
									title: '删除订单失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			// 去购物
			goShopping() {
				uni.switchTab({
					url: '/pages/mall/mall'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'order_list.scss';
</style>